import React, { Component, Fragment } from 'react';
import router from 'umi/router';
import {
  Form,
  Input,
  Select,
  Button,
  Row,
  Col,
  message,
  Card,
  Modal,
  Checkbox
} from 'antd';
import { connect } from 'dva';
import CusInputNumber from '@/components/CusInputNumber';
import ScrollSelect from '@/components/ScrollSelect';
import Range from '@/components/Range';
import isEmpty from 'lodash/isEmpty';
import api from '@/api';
import { SERVICE_STATUS } from '@/Constants';
import { maxLength } from '@/utils/form';
import { NAME_RULE, CODE_RULE } from '@/Constants/rules';

const FormItem = Form.Item;
const { Option } = Select;

@connect(({ base, service, supplier, loading, product }) => ({
  serviceTypes: base.serviceTypes,
  cargoTypes: base.cargoTypes,
  timeUnits: base.timeUnits,
  currentService: product.currentService,
  valueServices: service.valueServices,
  suppliers: supplier.suppliers,
  transRequirement: service.transRequirement,
  loading: loading.effects['product/queryServiceById'],
  creating: loading.effects['service/add'],
  updating: loading.effects['service/update'],
  submitAuditLoading: loading.effects['service/submitAudit'],
  auditLoading: loading.effects['service/audit'],
  unlockLoading: loading.effects['service/start'],
  lockLoading: loading.effects['service/stop'],

}))
@Form.create()
class BaseView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mode: isEmpty(props.currentService) ? 'add' : 'view',
      suppliers: [],
      pagination: {},
      searchVal: '',
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'base/fetchServiceTypes' });
    dispatch({ type: 'base/fetchCargoTypes' });
    dispatch({ type: 'base/fetchTimeUnits' });
    dispatch({ type: 'service/fetchValueServices' });
    dispatch({ type: 'service/queryTransRequirement', payload: { queryParams: { catalog: 'biz.service.transport' } } });
  }

  componentWillReceiveProps(nextProps) {
    const { mode } = this.state;
    if (!isEmpty(nextProps.currentService) && mode === 'add') {
      this.setState({ mode: 'view' });
    }
  }

  handleSave = () => {
    const { dispatch, form, creating, location } = this.props;
    let serviceType = location.query.serviceType
    let id;
    let productType = location.pathname.split('/')[2]
    switch (productType) {
      case 'today':
        id = 10000
        break;
      case 'tomorrow':
        id = 10001
        break;
      case 'time':
        id = 10002
        break
      default:
        id = 10000
    }
    if (creating) return
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      let payload = {
        ...fieldsValue,
        // weightLimitMin: fieldsValue.weightRange.start,
        // weightLimitMax: fieldsValue.weightRange.end,
        productId: id,
        nodeId: location.query.nodeId,
        phaseId: location.query.phaseId,
        typeCode: location.query.serviceType
      };
      if (fieldsValue.supplierId) {
        payload.supplierId = fieldsValue.supplierId.key;
      }
      if (fieldsValue.carrier) {
        payload.carrierId = fieldsValue.carrier.key
      }
      if (fieldsValue.airport) {
        payload.airport = fieldsValue.airport.key
      }
      if (serviceType === 'ST001' || serviceType === 'ST005') {
        if (!payload.transport) {
          form.setFields({ transport: { value: undefined, errors: [new Error('请选择运输要求')] } })
          return
        }
      }
      if (serviceType === 'ST002') {
        //航司必填
        if (!payload.carrierId) {
          form.setFields({ carrier: { value: undefined, errors: [new Error('请选择航司')] } })
          return
        }
      }
      dispatch({
        type: 'product/newCreateService',
        payload: {
          data: payload,
        },
      }).then(res => {
        if (res.errorCode === 0) {
          dispatch({
            type: 'product/queryServiceById',
            payload: {
              pathParams: {
                id: res.data,
              },
            },
          });
          form.resetFields();
          message.success('添加成功');
          router.push(`${location.pathname}${location.search}&serviceId=${res.data}`)
        }
      });
    });
  };

  handleUpdate = () => {
    const { dispatch, form, currentService, updating, location } = this.props;
    let serviceType = location.query.serviceType
    let id;
    let productType = location.pathname.split('/')[2]
    switch (productType) {
      case 'today':
        id = 10000
        break;
      case 'tomorrow':
        id = 10001
        break;
      case 'time':
        id = 10002
        break
      default:
        id = 10000
    }
    if (updating) return
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      let payload = {
        ...currentService,
        ...fieldsValue,
        // estimatedTime: fieldsValue.estimatedTime || 0,
        // weightLimitMin: fieldsValue.weightRange.start || 0,
        // weightLimitMax: fieldsValue.weightRange.end || 0,
        productId: id,
        nodeId: location.query.nodeId,
        phaseId: location.query.phaseId,
      };
      if (fieldsValue.supplierId) {
        payload.supplierId = fieldsValue.supplierId.key;
      }
      if (fieldsValue.carrier) {
        payload.carrierId = fieldsValue.carrier.key
      }
      if (fieldsValue.airport) {
        payload.airport = fieldsValue.airport.key
      }
      if (!fieldsValue.transport) {
        payload.transport = ''
      }
      if (serviceType === 'ST001' || serviceType === 'ST005') {
        if (!payload.transport) {
          form.setFields({ transport: { value: undefined, errors: [new Error('请选择运输要求')] } })
          return
        }
      }
      if (serviceType === 'ST002') {
        //航司必填
        if (!payload.carrierId) {
          form.setFields({ carrier: { value: undefined, errors: [new Error('请选择航司')] } })
          return
        }
      }
      dispatch({
        type: 'product/newUpdateService',
        payload: {
          pathParams: {
            id: currentService.id,
          },
          data: payload,
        },
      }).then(res => {
        if (res.errorCode === 0) {
          dispatch({
            type: 'product/queryServiceById',
            payload: {
              pathParams: {
                id: currentService.id,
              },
            },
          });
          form.resetFields();
          this.setState({
            mode: 'view',
          });
          message.success('更新成功');
        }
      });
    });
  };

  checkCode = (rule, value = '', callback) => {
    const { mode } = this.state;
    const { currentService } = this.props;
    if (value === '') {
      return callback();
    }
    let payload = {
      [rule.field]: value,
    };
    if (mode === 'edit') {
      payload.id = currentService.id;
    }
    api.service
      .checkCode({
        queryParams: payload,
      })
      .then(res => {
        if (!res.data) {
          callback(rule.message);
        } else {
          callback();
        }
      });
  };


  handleOnline = () => {
    const { dispatch, location, unlockLoading } = this.props;
    if (unlockLoading) return
    Modal.confirm({
      title: '启用服务',
      content: '确定启用此服务吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return dispatch({
          type: 'service/start',
          payload: {
            data: [location.query.serviceId],
          },
        }).then(res => {
          if (res.errorCode === 0) {
            dispatch({
              type: 'product/queryServiceById',
              payload: {
                pathParams: {
                  id: location.query.serviceId,
                },
              },
            });
            message.success('启用成功');
          }
        });
      },
    });
  };

  handleOffline = () => {
    const { dispatch, location, lockLoading } = this.props;
    if (lockLoading) return
    Modal.confirm({
      title: '停用服务',
      content: '确定停用此服务吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return dispatch({
          type: 'service/stop',
          payload: {
            data: [location.query.serviceId],
          },
        }).then(res => {
          if (res.errorCode === 0) {
            dispatch({
              type: 'product/queryServiceById',
              payload: {
                pathParams: {
                  id: location.query.serviceId,
                },
              },
            });
            message.success('停用成功');
          }
        });
      },
    });
  };

  querySuppliers = params => {
    return api.supplier.shortQuery({
      queryParams: params,
    });
  };
  queryAirCompany = params => {
    return api.base.queryCarrierCompanies({ queryParams: params });
  };
  queryAirports = params => {
    return api.base.queryAirport({
      queryParams: params,
    });
  };
  checkSupplier = (rule, value, callback) => {
    if (isEmpty(value)) {
      return callback(rule.message)
    }
    if (!value.key) {
      return callback(rule.message)
    }
    return callback()
  }
  handleCheckAll = (e) => {
    const { form: { setFieldsValue }, cargoTypes } = this.props;
    let cargoTypeCodeList = []
    if (e.target.checked) {
      cargoTypeCodeList = cargoTypes.map(item => item.code)
    }
    setFieldsValue({ cargoTypeCodeList })
  }
  renderForm = () => {
    const {
      form: { getFieldDecorator, getFieldValue },
      cargoTypes,
      currentService,
      creating,
      updating,
      location,
      valueServices,
      timeUnits,
      transRequirement
    } = this.props;
    const { mode } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
      },
    };
    let serviceType = location.query.serviceType
    return (
      <div>
        {
          serviceType === 'STS004' ? <>
            <FormItem label="航&ensp;班&ensp;号" {...formItemLayout}>
              {getFieldDecorator('name', {
                rules: [
                  { required: true, message: '请输入航班号', whitespace: true },
                  {
                    pattern: NAME_RULE.PATTERN,
                    message: NAME_RULE.MESSAGE,
                  },
                ],
                initialValue: currentService.name,
              })(<Input onInput={e => maxLength(e, 30)} style={{ width: 300 }} />)}
            </FormItem>
            <FormItem label="仓位限制" {...formItemLayout}>
              {getFieldDecorator('weightRange', {
                rules: [{ validator: Range.validate, message: '下限必须小于上限' }],
                initialValue: {
                  start: currentService.weightLimitMin,
                  end: currentService.weightLimitMax,
                },
              })(
                <Range
                  precision={3}
                  max={99999}
                  min={0.001}
                  extra={<span style={{ marginLeft: 10 }}>kg</span>}
                />
              )}
            </FormItem>
            <FormItem label="货物类型" {...formItemLayout} required>
              {getFieldDecorator('cargoTypeCodeList', {
                rules: [{ required: true, message: '货物类型不能为空' }],
                initialValue: currentService.cargoTypeCodeList,
              })(
                <Select style={{ width: 300 }} mode="multiple">
                  {cargoTypes.map((cargoType, index) => (
                    <Option key={index} value={cargoType.code}>
                      {cargoType.name}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
            <FormItem label="供&ensp;应&ensp;商" {...formItemLayout} required={true}>
              {getFieldDecorator('supplierId', {
                rules: [
                  { validator: this.checkSupplier, message: '请选择供应商' },
                ],
                initialValue: !isEmpty(currentService) ? {
                  key: currentService.supplierId,
                  label: `${currentService.supplierName}(${currentService.supplierCode})`,
                } : {
                    key: '',
                    label: ''
                  },
              })(
                <ScrollSelect
                  style={{ width: 300 }}
                  search={this.querySuppliers}
                  optionKey="id"
                  filterOption={false}
                  allowClear
                />
              )}
            </FormItem>
            <FormItem label="备&#12288;&#12288;注" {...formItemLayout}>
              {getFieldDecorator('description', {
                initialValue: currentService.description,
              })(<Input.TextArea onInput={e => maxLength(e, 140)} style={{ width: 300 }} />)}
            </FormItem>
          </>
            :
            <>
              <FormItem label="名&emsp;&emsp;称" {...formItemLayout}>
                {getFieldDecorator('name', {
                  rules: [
                    { required: true, message: '名称不能为空', whitespace: true },
                    {
                      pattern: NAME_RULE.PATTERN,
                      message: NAME_RULE.MESSAGE,
                    },
                  ],
                  initialValue: currentService.name,
                })(<Input onInput={e => maxLength(e, 30)} style={{ width: 300 }} />)}
              </FormItem>
              <FormItem label="编&#12288;&#12288;码" {...formItemLayout}>
                {getFieldDecorator('code', {
                  rules: [
                    { required: true, message: '编码不能为空', whitespace: true },
                    { pattern: CODE_RULE.PATTERN, message: CODE_RULE.MESSAGE },
                    { validator: this.checkCode, message: '编码已存在' },
                  ],
                  validateTrigger: 'onBlur',
                  initialValue: currentService.code,
                })(
                  <Input
                    onInput={e => maxLength(e, 15)}
                    style={{ width: 300 }}
                    disabled={mode === 'edit'}
                  />
                )}
              </FormItem>
              <FormItem label="航&emsp;&emsp;司" {...formItemLayout}>
                {getFieldDecorator('carrier', {
                  validateTrigger: 'onBlur',
                  initialValue: currentService.carrierId ? { key: currentService.carrierId, label: currentService.carrierName } : undefined
                })(
                  <ScrollSelect
                    allowClear
                    search={this.queryAirCompany}
                    showKey={false}
                    // optionCode="iataCode"
                    optionKey="id"
                    style={{ width: 300 }}
                  />
                )}
              </FormItem>
              <FormItem label="运输要求" {...formItemLayout}>
                {getFieldDecorator('transport', {
                  initialValue: currentService.transport,
                  validateTrigger: 'onBlur',
                })(
                  <Select style={{ width: 300 }} allowClear>
                    {
                      transRequirement.map(item => (
                        <Option key={item.code} value={item.code}>{item.name}</Option>
                      ))
                    }
                  </Select>
                )}
              </FormItem>
              <FormItem label="服务机场" {...formItemLayout}>
                {getFieldDecorator('airport', {
                  rules: [
                    {
                      required: true, message: '请选择服务机场'
                    }
                  ],
                  validateTrigger: 'onBlur',
                  initialValue: currentService.airport ? { key: currentService.airport, label: currentService.airportName } : undefined
                })(
                  <ScrollSelect
                    allowClear
                    search={this.queryAirports}
                    optionKey="code"
                    style={{ width: 300 }}
                  />
                )}
              </FormItem>
              {/* <FormItem label="增值服务" {...formItemLayout}>
                {getFieldDecorator('valueAddedServiceCodeList', {
                  initialValue: currentService.valueAddedServiceCodeList,
                })(
                  <Select style={{ width: 300 }} mode="multiple">
                    {valueServices.map(vs => (
                      <Option key={vs.code} value={vs.code}>
                        {vs.name}
                      </Option>
                    ))}
                  </Select>
                )}
              </FormItem>
              <FormItem label="预估时效" {...formItemLayout}>
                {getFieldDecorator('estimatedTime', {
                  initialValue: currentService.estimatedTime,
                })(
                  <CusInputNumber
                    max={99999}
                    min={0}
                    style={{ width: 170, marginRight: 10 }}
                    precision={3}
                  />
                )}
                {getFieldDecorator('estimatedUnit', {
                  initialValue: currentService.estimatedUnit || 'DAY',
                })(
                  <Select optionFilterProp="children" style={{ width: 120 }}>
                    {timeUnits.map(item => (
                      <Option key={item.code} value={item.code}>
                        {item.name}
                      </Option>
                    ))}
                  </Select>
                )}
              </FormItem>
              <FormItem label="服务内容" {...formItemLayout}>
                {getFieldDecorator('serviceContent', {
                  initialValue: currentService.serviceContent,
                })(<Input.TextArea onInput={e => maxLength(e, 140)} style={{ width: 300 }} />)}
              </FormItem>
              <FormItem label="重量限制" {...formItemLayout}>
                {getFieldDecorator('weightRange', {
                  rules: [{ validator: Range.validate, message: '下限必须小于上限' }],
                  initialValue: {
                    start: currentService.weightLimitMin,
                    end: currentService.weightLimitMax,
                  },
                })(
                  <Range
                    precision={3}
                    max={99999}
                    min={0.001}
                    extra={<span style={{ marginLeft: 10 }}>kg</span>}
                  />
                )}
              </FormItem> */}
              <FormItem label="货物类型" {...formItemLayout} required>
                {getFieldDecorator('cargoTypeCodeList', {
                  rules: [{ required: true, message: '货物类型不能为空' }],
                  initialValue: currentService.cargoTypeCodeList,
                })(
                  <Select style={{ width: 300 }} mode="multiple">
                    {cargoTypes.map((cargoType, index) => (
                      <Option key={index} value={cargoType.code}>
                        {cargoType.name}
                      </Option>
                    ))}
                  </Select>
                )}
                <Checkbox style={{ marginLeft: 10 }} onChange={this.handleCheckAll}>全选</Checkbox>
              </FormItem>
              <FormItem label="供&ensp;应&ensp;商" {...formItemLayout} required={true}>
                {getFieldDecorator('supplierId', {
                  rules: [
                    { validator: this.checkSupplier, message: '请选择供应商' },
                  ],
                  initialValue: !isEmpty(currentService) ? {
                    key: currentService.supplierId,
                    label: `${currentService.supplierName}(${currentService.supplierCode})`,
                  } : {
                      key: '',
                      label: ''
                    },
                })(
                  <ScrollSelect
                    style={{ width: 300 }}
                    search={this.querySuppliers}
                    optionKey="id"
                    filterOption={false}
                    allowClear
                  />
                )}
              </FormItem>
              <FormItem label="备&#12288;&#12288;注" {...formItemLayout}>
                {getFieldDecorator('description', {
                  initialValue: currentService.description,
                })(<Input.TextArea onInput={e => maxLength(e, 140)} style={{ width: 300 }} />)}
              </FormItem>
            </>
        }
        <Row type="flex">
          <Col span={5} />
          {mode === 'add' && (
            <Button
              type="primary"
              style={{ marginLeft: 110 }}
              onClick={this.handleSave}
              loading={creating}
            >
              保存
            </Button>
          )}
          {mode === 'edit' && (
            <Fragment>
              <Button style={{ marginLeft: 50 }} onClick={() => this.setState({ mode: 'view' })}>
                取消
              </Button>
              <Button
                type="primary"
                style={{ marginLeft: 30 }}
                onClick={this.handleUpdate}
                loading={updating}
              >
                保存
              </Button>
            </Fragment>
          )}
        </Row>
      </div>
    );
  };

  renderView = () => {
    const { currentService, location } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
      },
    };
    let serviceType = location.query.serviceType
    return (
      <div style={{ position: 'relative' }}>
        <div style={{ position: 'absolute', right: 20, top: 15, zIndex: 2 }}>
          <Button
            type="primary"
            style={{ marginRight: 10 }}
            onClick={() => this.setState({ mode: 'edit' })}
          >
            编辑
            </Button>
        </div>
        {
          serviceType === 'ST004' ?
            <>
              <FormItem label="航&ensp;班&ensp;号" {...formItemLayout}>
                {currentService.name}
              </FormItem>
              <FormItem label="仓位限制" {...formItemLayout}>
                {currentService.weightLimitMin}-{currentService.weightLimitMax}
                {currentService.weightLimitMin ? `(${currentService.weightLimitUnitCode})` : ''}
              </FormItem>
              <FormItem label="货物类型" {...formItemLayout}>
                {currentService.cargoTypeNameList.toString()}
              </FormItem>
              <FormItem label="供&ensp;应&ensp;商" {...formItemLayout}>
                {currentService.supplierName}({currentService.supplierCode})
              </FormItem>
              <FormItem label="备&#12288;&#12288;注" {...formItemLayout}>
                {currentService.description}
              </FormItem>
            </> :
            <>
              <FormItem label="名&emsp;&emsp;称" {...formItemLayout}>
                {currentService.name}
              </FormItem>
              <FormItem label="编&#12288;&#12288;码" {...formItemLayout}>
                {currentService.code}
              </FormItem>
              <FormItem label="航&emsp;&emsp;司" {...formItemLayout}>
                {currentService.carrierName}
              </FormItem>
              <FormItem label="运输要求" {...formItemLayout}>
                {currentService.transportName}
              </FormItem>
              <FormItem label="服务机场" {...formItemLayout}>
                {currentService.airportName}
              </FormItem>
              {/* <FormItem label="增值服务" {...formItemLayout}>
                {currentService.valueAddedServiceNameList.toString()}
              </FormItem>
              <FormItem label="预估时效" {...formItemLayout}>
                {currentService.estimatedTime}
                {currentService.estimatedTime ? currentService.estimatedUnitName : ''}
              </FormItem>
              <FormItem label="服务内容" {...formItemLayout}>
                {currentService.serviceContent}
              </FormItem>
              <FormItem label="重量限制" {...formItemLayout}>
                {currentService.weightLimitMin}-{currentService.weightLimitMax}
                {currentService.weightLimitMin ? `(${currentService.weightLimitUnitCode})` : ''}
              </FormItem> */}
              <FormItem label="货物类型" {...formItemLayout}>
                {currentService.cargoTypeNameList.toString()}
              </FormItem>
              <FormItem label="供&ensp;应&ensp;商" {...formItemLayout}>
                {currentService.supplierName}({currentService.supplierCode})
              </FormItem>
              <FormItem label="备&#12288;&#12288;注" {...formItemLayout}>
                {currentService.description}
              </FormItem>
            </>
        }

      </div>
    );
  };

  render() {
    const { mode } = this.state;
    const { loading } = this.props;
    let renderer = null;
    if (mode === 'add' || mode === 'edit') renderer = this.renderForm();
    if (mode === 'view') renderer = this.renderView();
    return (
      <Card bordered={false} loading={loading}>
        {renderer}
      </Card>
    );
  }
}

export default BaseView;
